package com.zhuang.singleton.type2;

/**
 * @Classname SingletonTest02
 * @Description  静态代码块
 * @Date 2021/3/17 9:35
 * @Created by dell
 */

public class SingletonTest02 {
    public static void main(String[] args) {
        Singleton2 instance = Singleton2.getInstance();
        Singleton2 instance2 = Singleton2.getInstance();
        //判断是否为单例
        System.out.println(instance == instance2);
        System.out.println("intstance的哈希值" + instance.hashCode());
        System.out.println("intstance2的哈希值" + instance2.hashCode());
    }
}

class Singleton2 {

    //1.构造器私有化，外部能new、
    private Singleton2() {

    }

    //本类内部创建对象实例
    private static Singleton2 instance;

    /*
    在静态代码块中创建对象
     */
    static {
        instance = new Singleton2();
    }

    //对外部提供一个公有的静态方法
    public static Singleton2 getInstance() {
        return instance;
    }
}